<template>
  <view class="viewport">
    <fui-nav-bar
      isOccupy
      isFixed
      background="#0052D9"
      title="派工"
      color="#fff"
      @leftClick="leftClick"
    >
      <fui-icon color="#fff" name="arrowleft"></fui-icon>
    </fui-nav-bar>

    <view class="warp">
      <!-- 维修工单标题 -->
      <view class="section-title">
        <view class="line"></view>
        <text>维修工单</text>
      </view>

      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">工单号码</text>
          <text class="value">{{ repairStore.orderInfo.repairCode }}</text>
        </view>

        <view class="form-item">
          <text class="label">工单主题</text>
          <text class="value">{{ repairStore.orderInfo.repairSubject }}</text>
        </view>

        <view class="form-item">
          <text class="label">工单类型</text>
          <text class="value">{{ repairStore.orderInfo.repairType }}</text>
        </view>

        <view class="form-item">
          <text class="label required">维修班组</text>
          <view class="input-wrapper" @tap="selectTeam">
            <text :class="{ placeholder: !selectedTeamNames }">{{
              selectedTeamNames || "请选择维修班组"
            }}</text>
            <fui-icon name="arrowright" color="#BDBDBD"></fui-icon>
          </view>
        </view>

        <view class="form-item">
          <text class="label required">维修负责人</text>
          <view class="input-wrapper" @tap="selectManager">
            <text :class="{ placeholder: !selectedLeaderName }">{{
              selectedLeaderName || "请选择维修负责人"
            }}</text>
            <fui-icon name="arrowright" color="#BDBDBD"></fui-icon>
          </view>
        </view>

        <view class="form-item">
          <text class="label">其他维修人</text>
          <view class="input-wrapper" @tap="selectOthers">
            <text :class="{ placeholder: !selectedOtherStaffNames }">{{
              selectedOtherStaffNames || "请选择其他维修人"
            }}</text>
            <fui-icon name="arrowright" color="#BDBDBD"></fui-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="submit-btn" @tap="onSubmit">提交</view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import {
  submitAssign,
  getOrderDetail,
} from "@/pages/api/subpkg_index/dispatching.js";
import { useRepairStore } from "@/store/modules/repair.js";

const repairStore = useRepairStore();

// 选中的班组数据
const selectedTeam = ref(null);
// 选中的维修负责人
const selectedLeader = ref(null);
// 选中的其他维修人员
const otherStaff = ref([]);

// 计算选中的班组名称
const selectedTeamNames = computed(() => {
  if (!selectedTeam.value) return "";
  return selectedTeam.value.teamName || "";
});

// 计算选中的负责人名称
const selectedLeaderName = computed(() => {
  if (!selectedLeader.value) return "";
  return selectedLeader.value.workerName || "";
});

// 计算选中的其他人员名称
const selectedOtherStaffNames = computed(() => {
  if (!otherStaff.value.length) return "";
  return otherStaff.value.map((staff) => staff.workerName).join("、");
});

const leftClick = () => {
  uni.navigateBack();
};

// 选择维修班组
const selectTeam = () => {
  uni.navigateTo({
    url: "/subpkg_index/dispatching/team",
  });
};

// 选择维修负责人
const selectManager = () => {
  if (!selectedTeam.value) {
    uni.showToast({
      title: "请先选择维修班组",
      icon: "none",
    });
    return;
  }
  uni.navigateTo({
    url: `/subpkg_index/dispatching/staff?type=leader&team=${encodeURIComponent(
      JSON.stringify(selectedTeam.value)
    )}`,
  });
};

// 选择其他维修人
const selectOthers = () => {
  if (!selectedTeam.value) {
    uni.showToast({
      title: "请先选择维修班组",
      icon: "none",
    });
    return;
  }
  uni.navigateTo({
    url: `/subpkg_index/dispatching/staff?type=others&team=${encodeURIComponent(
      JSON.stringify(selectedTeam.value)
    )}`,
  });
};

// 提交
const onSubmit = async () => {
  if (!selectedTeam.value) {
    uni.showToast({
      title: "请选择维修班组",
      icon: "none",
    });
    return;
  }
  if (!selectedLeader.value) {
    uni.showToast({
      title: "请选择维修负责人",
      icon: "none",
    });
    return;
  }

  try {
    // 构造提交数据
    const submitData = {
      id: repairStore.orderInfo.id,
      repairCode: repairStore.orderInfo.repairCode,
      repairSubject: repairStore.orderInfo.repairSubject,
      repairType: repairStore.orderInfo.repairType,
      status: repairStore.orderInfo.status,
      repairTeam: selectedTeam.value.teamName,
      repairStaff: selectedLeader.value.workerName,
      otherStaff: otherStaff.value.length
        ? otherStaff.value.map((staff) => staff.workerName).join(",")
        : "",
    };

    console.log("提交的数据:", submitData);

    uni.showLoading({
      title: "提交中...",
    });

    const res = await submitAssign(submitData);

    uni.hideLoading();

    if (res.code === 200) {
      uni.showToast({
        title: "派工成功",
        icon: "success",
      });

      // 延迟返回上一页
      setTimeout(() => {
        // 清空store中的工单信息
        repairStore.clearOrderInfo();
        uni.navigateBack();

        // 通知上一页刷新
        uni.$emit("refreshOrderList");
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || "派工失败",
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("派工提交失败:", error);
    uni.showToast({
      title: "派工失败，请重试",
      icon: "none",
    });
  }
};

// 监听班组选择更新事件
const handleTeamUpdate = (data) => {
  if (data && data.selectedTeam) {
    selectedTeam.value = data.selectedTeam;
  }
};

// 监听人员选择更新事件
const handleStaffUpdate = (data) => {
  if (!data) return;

  if (data.type === "leader") {
    // 维修负责人只取第一个
    selectedLeader.value = data.selectedStaff[0] || null;
  } else if (data.type === "others") {
    // 其他维修人员可以多选
    otherStaff.value = data.selectedStaff || [];
  }
};

// 获取工单详情
const getDetail = async (id) => {
  try {
    uni.showLoading({
      title: "加载中...",
    });
    const res = await getOrderDetail(id);
    uni.hideLoading();
    if (res.code === 200) {
      // 更新工单信息到store
      repairStore.setOrderInfo({
        id: res.data.id,
        repairCode: res.data.repairCode,
        repairSubject: res.data.repairSubject,
        repairType: res.data.repairType,
        status: res.data.status,
      });
    } else {
      uni.showToast({
        title: res.msg || "获取工单详情失败",
        icon: "none",
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("获取工单详情失败：", error);
    uni.showToast({
      title: "获取工单详情失败",
      icon: "none",
    });
  }
};

// 获取当前页面实例
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const options = currentPage.$page?.options || {};

onMounted(async () => {
  // 添加事件监听
  uni.$on("updateTeam", handleTeamUpdate);
  uni.$on("updateStaff", handleStaffUpdate);

  // 获取工单详情
  if (options.id) {
    await getDetail(options.id);
  } else {
    uni.showToast({
      title: "工单ID不能为空",
      icon: "none",
    });
  }
});

onUnmounted(() => {
  // 移除事件监听
  uni.$off("updateTeam", handleTeamUpdate);
  uni.$off("updateStaff", handleStaffUpdate);
  // 清空store中的工单信息
  repairStore.clearOrderInfo();
});

// 修改 onLoad 方法
defineExpose({
  onLoad: async (options) => {
    console.log("页面参数:", options);
    if (!options.id) {
      uni.showToast({
        title: "工单ID不能为空",
        icon: "none",
      });
      return;
    }
    await getDetail(options.id);
  },
});
</script>

<style lang="scss" scoped>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.warp {
  flex: 1;
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.section-title {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
  background-color: #fff;
  padding: 30rpx 20rpx;
  border-radius: 8rpx;

  .line {
    width: 8rpx;
    height: 32rpx;
    background-color: #0052d9;
    margin-right: 16rpx;
  }

  text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.form-content {
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 20rpx;
  margin-top: 20rpx;

  .form-item {
    padding: 30rpx 0;
    border-bottom: 2rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }

    .label {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 16rpx;
      display: block;

      &.required::before {
        content: "*";
        color: #ff4d4f;
        margin-right: 4rpx;
      }
    }

    .value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }

    .input-wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;

      text {
        font-size: 28rpx;

        &.placeholder {
          color: #bdbdbd;
        }

        &:not(.placeholder) {
          color: #333;
        }
      }
    }
  }
}

.submit-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #0052d9;
  color: #fff;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
